package handler

import (
	"encoding/json"
	"log"
	"net/http"

	"go-todo-app/db"
	"go-todo-app/model"

	"github.com/gorilla/mux"
	"gorm.io/gorm"
)

type Response struct {
	Success bool        `json:"success"`
	Data    interface{} `json:"data,omitempty"`
	Error   string      `json:"error,omitempty"`
}

// CreateTodoHandler 创建任务
func CreateTodoHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	var todo model.Todo
	if err := json.NewDecoder(r.Body).Decode(&todo); err != nil {
		json.NewEncoder(w).Encode(Response{Success: false, Error: "请求体错误: " + err.Error()})
		return
	}

	if todo.Title == "" {
		json.NewEncoder(w).Encode(Response{Success: false, Error: "标题不能为空"})
		return
	}

	// GORM 创建
	result := db.DB.Create(&todo)
	if result.Error != nil {
		json.NewEncoder(w).Encode(Response{Success: false, Error: "创建失败: " + result.Error.Error()})
		return
	}

	json.NewEncoder(w).Encode(Response{Success: true, Data: todo})
}

// GetAllTodosHandler 获取所有任务
func GetAllTodosHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	var todos []model.Todo
	result := db.DB.Order("id desc").Find(&todos)
	if result.Error != nil {
		json.NewEncoder(w).Encode(Response{Success: false, Error: "查询失败: " + result.Error.Error()})
		return
	}

	json.NewEncoder(w).Encode(Response{Success: true, Data: todos})
}

// GetTodoByIDHandler 获取单个任务
func GetTodoByIDHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r) // 获取路径参数
	id := vars["id"]    // 拿到 :id 的值
	if id == "" {
		json.NewEncoder(w).Encode(Response{Success: false, Error: "ID 不能为空"})
		return
	}
	log.Println("GetTodoByIDHandler", id)
	w.Header().Set("Content-Type", "application/json")

	var todo model.Todo
	result := db.DB.First(&todo, id)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			w.WriteHeader(http.StatusNotFound)
			json.NewEncoder(w).Encode(Response{Success: false, Error: "任务不存在"})
		} else {
			json.NewEncoder(w).Encode(Response{Success: false, Error: "查询失败: " + result.Error.Error()})
		}
		return
	}

	json.NewEncoder(w).Encode(Response{Success: true, Data: todo})
}

// UpdateTodoHandler 更新任务
func UpdateTodoHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	vars := mux.Vars(r) // 获取路径参数
	id := vars["id"]    // 拿到 :id 的值
	if id == "" {
		json.NewEncoder(w).Encode(Response{Success: false, Error: "ID 不能为空"})
		return
	}

	var updatedTodo model.Todo
	if err := json.NewDecoder(r.Body).Decode(&updatedTodo); err != nil {
		json.NewEncoder(w).Encode(Response{Success: false, Error: "请求体错误: " + err.Error()})
		return
	}
	// if updatedTodo.Title == "" {
	// 	json.NewEncoder(w).Encode(Response{Success: false, Error: "标题不能为空"})
	// 	return
	// }
	// 更新
	var todo model.Todo
	result := db.DB.First(&todo, id)
	if result.Error != nil {
		w.WriteHeader(http.StatusNotFound)
		json.NewEncoder(w).Encode(Response{Success: false, Error: "任务不存在"})
		return
	}
	if updatedTodo.Title != "" {
		todo.Title = updatedTodo.Title
	}
	todo.Done = updatedTodo.Done
	// _data, _ := json.MarshalIndent(todo, "", "    ")
	// log.Println("todo", string(_data))
	db.DB.Save(&todo)

	json.NewEncoder(w).Encode(Response{Success: true, Data: todo})
}

// DeleteTodoHandler 删除任务
func DeleteTodoHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	vars := mux.Vars(r) // 获取路径参数
	id := vars["id"]    // 拿到 :id 的值
	if id == "" {
		json.NewEncoder(w).Encode(Response{Success: false, Error: "ID 不能为空"})
		return
	}

	result := db.DB.Delete(&model.Todo{}, id)
	if result.Error != nil {
		json.NewEncoder(w).Encode(Response{Success: false, Error: "删除失败: " + result.Error.Error()})
		return
	}

	if result.RowsAffected == 0 {
		w.WriteHeader(http.StatusNotFound)
		json.NewEncoder(w).Encode(Response{Success: false, Error: "任务不存在"})
		return
	}

	json.NewEncoder(w).Encode(Response{Success: true, Data: map[string]string{"message": "删除成功"}})
}
